package cn.didi.feidi.androidorder.fragment.personal;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.AuthResult;
import cn.didi.feidi.androidorder.model.PayResult;

/**
 * 我的钱包-充值
 */
public class PersonRechargeFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonRechargeFragment";

    private EditText rechargeValues;
    private TextView commitTv;

    private String toRechargeMoney;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    Log.d(TAG, resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        makeToast("支付成功");
                        getActivity().finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        makeToast("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        makeToast("授权成功");
                    } else {
                        // 其他状态值则为授权失败
                        makeToast("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonRechargeFragment newInstance(Bundle bundle) {
        PersonRechargeFragment fragment = new PersonRechargeFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_recharge, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }


    @Override
    protected void initViews(View rootView) {
        rechargeValues = (EditText) rootView.findViewById(R.id.person_recharge_edit_money);
        commitTv = (TextView) rootView.findViewById(R.id.person_recharge_commit_tv);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void addListener() {
        commitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  执行充值操作
                toRechargeMoney = rechargeValues.getText().toString().trim();

                if (toRechargeMoney == null || "".equals(toRechargeMoney)) {
                    makeToast("输入金额不能为空");
                    return;
                }

                if (Float.parseFloat(toRechargeMoney) <= 0) {
                    makeToast("输入金额必须大于零");
                    return;
                }

                Map<String, String> params = new HashMap<>();

                params.put("userId", UserManager.getUserId());
                params.put("token", UserManager.getToken());
                params.put("amount", toRechargeMoney);

                executeRequest(new AppActionRequest<String>(Api.ALIPAY_GET_ALIPAY_SIGNED_CHARGE, params,
                        new TypeToken<ApiResponse<String>>() {
                        }.getType(), new ActionCallbackListener<String>() {
                    @Override
                    public void onSuccess(String message, final String data) {
                        if (data != null) {
                            Runnable payRunnable = new Runnable() {

                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(mActivity);
                                    Map<String, String> result = alipay.payV2(data, true);
                                    Log.i("msp", result.toString());

                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        } else {
                            makeToast("success" + message);
                            Log.d(TAG, message);
                        }
                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                        switch (errorEvent) {
                            default:
                                makeToast("未知错误");
                                break;
                        }
                    }
                }));
            }
        });
        /**
         * 限定2位小数
         */
        rechargeValues.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        rechargeValues.setText(s);
                        rechargeValues.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    rechargeValues.setText(s);
                    rechargeValues.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        rechargeValues.setText(s.subSequence(0, 1));
                        rechargeValues.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
}
